/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.oapi.alct56.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.aliyunocr.utils.HttpUtils;
import org.jeecg.modules.third.oapi.alct56.constant.OapiAlct56Constant;
import org.jeecg.modules.third.oapi.alct56.dto.AlctApiBaseResDTO;
import org.jeecg.modules.third.oapi.alct56.dto.ApiTokenResDTO;
import org.jeecg.modules.third.oapi.alct56.dto.req.image.ShippingImageDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 航信或陆交辽宁税务平台,此类中的方法用作模拟App侧调用税务系统接口，直接在后台伪造App请求进行运单装卸货、图片上传等操作
 * 辽宁省税务对接
 */
@Service
@Slf4j
public class AppAlct56Service {

    @Value(value="${ln-tax-platform.domain:http://61.161.232.25:31002/freight-tax}")
    private String LN_TAX_DOMIAN;

    @Value(value="${ln-tax-platform.enterpriseCode:E0023020}")
    private String LN_TAX_ENTERPRISE;

    @Value(value="${ln-tax-platform.enterpriseIdentity:aea8ac9bd73c945aebe5ca3dc806e254}")
    private String LN_TAX_IDENTITY;

    @Value(value="${ln-tax-platform.enterpriseKey:e2cd00a2dd831e5435699b2d09e3f259}")
    private String LN_TAX_KEY;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取Token
     * @return
     */
    public String getToken(String driverIdentity) {

        if (StrUtil.isEmpty(LN_TAX_DOMIAN) || StrUtil.isEmpty(LN_TAX_ENTERPRISE)
         || StrUtil.isEmpty(LN_TAX_IDENTITY) || StrUtil.isEmpty(LN_TAX_KEY) || StrUtil.isEmpty(driverIdentity)) {
            log.error("航信税务平台参数配置错误{} {} {} {} {}", LN_TAX_DOMIAN, LN_TAX_ENTERPRISE, LN_TAX_IDENTITY, LN_TAX_KEY, driverIdentity);
            throw new JeecgBootException("航信税务平台参数配置错误");
        }

        //Object tokenObject = redisUtil.hasKey(OapiAlct56Constant.OAPIALCT56_TOKEN_KEY + "_" + driverIdentity) ?
        //        redisUtil.get(OapiAlct56Constant.OAPIALCT56_TOKEN_KEY + "_" + driverIdentity) : null;

        String token = StringUtils.EMPTY;
        //if (tokenObject == null) {
            String path = "/api/v1/openapi/apps/login";
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json; charset=UTF-8");
            Map<String, String> querys = new HashMap<>();
            // 拼装请求body的json字符串
            JSONObject requestObj = new JSONObject();

            log.info("{}, {}, {}， {}", LN_TAX_DOMIAN, LN_TAX_ENTERPRISE, LN_TAX_IDENTITY, LN_TAX_KEY);
            //{
            //    "enterpriseCode": "E0023020",
            //    "appIdentity": "aea8ac9bd73c945aebe5ca3dc806e254",
            //    "appKey": "e2cd00a2dd831e5435699b2d09e3f259",
            //    "driverIdentity": "130521198512171618"
            //}
            requestObj.put("enterpriseCode", LN_TAX_ENTERPRISE);
            requestObj.put("appIdentity", LN_TAX_IDENTITY);
            requestObj.put("appKey", LN_TAX_KEY);
            requestObj.put("driverIdentity", driverIdentity);
            String bodys = requestObj.toString();

            try {
                log.info("辽宁航信税务获取App侧Token请求 -> {} ", bodys);
                HttpResponse response = HttpUtils.doPost(LN_TAX_DOMIAN, path, "POST", headers, querys, bodys);
                int stat = response.getStatusLine().getStatusCode();
                if (stat != 200) {
                    log.info("辽宁航信税务App侧获取Token异常: :{}  | http header error msg:{} | Http body error msg: ",
                            stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                    return StringUtils.EMPTY;
                }
                String res = EntityUtils.toString(response.getEntity());
                log.info("辽宁航信税务获取App侧Token回执 <- {} ", res);
                ApiTokenResDTO result = JSONObject.parseObject(res, ApiTokenResDTO.class);
                if (result.getCode().equals("0") && StringUtils.isNotEmpty(result.getToken())) {

                    redisUtil.set(OapiAlct56Constant.OAPIALCT56_TOKEN_KEY + "_" + driverIdentity, result.getToken(), result.getExpiryIn());
                    redisUtil.set(OapiAlct56Constant.OAPIALCT56_REFRESHTOKEN_KEY + "_" + driverIdentity, result.getRefreshToken(), result.getExpiryIn());

                    return result.getToken();
                }

            } catch (Exception e) {
                log.info("OapiAlct56Service getToken Exception :{} ", e.getMessage());
            }
        //}

        //log.info("辽宁税务已获取到Token, {}", tokenObject.toString());
        //return tokenObject != null && StringUtils.isNotEmpty(tokenObject.toString())
        //        ? tokenObject.toString() : token;
        return StringUtils.EMPTY;
    }

    /**
     * token过期前1个小时或更早用refreshToken来获取新的token。
     * @return
     */
    public String getRefreshtoken(String driverIdentity){
        Object tokenObject  = redisUtil.hasKey(OapiAlct56Constant.OAPIALCT56_REFRESHTOKEN_KEY) ?
                redisUtil.get(OapiAlct56Constant.OAPIALCT56_REFRESHTOKEN_KEY) : null;
        if (tokenObject == null ) {
            return StringUtils.EMPTY;
        }
        String path = "/api/v1/openapi/enterprises/refresh-token/"+tokenObject.toString();
        Map <String, String> headers = new HashMap <>();
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();
        String bodys = "";
        try {
            HttpResponse response = HttpUtils.doPost(LN_TAX_DOMIAN, path, "POST", headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if(stat != 200){
                log.info("OapiAlct56Service getRefreshtoken Http code: :{}  | http header error msg:{} | Http body error msg: ",
                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                return StringUtils.EMPTY;
            }
            String res = EntityUtils.toString(response.getEntity());
            log.info("辽宁航信税务刷新Token回执 <- {} ",res);
            ApiTokenResDTO result = JSONObject.parseObject(res, ApiTokenResDTO.class);
            if(result.getCode().equals("0") && StringUtils.isNotEmpty(result.getToken())){
                redisUtil.set(OapiAlct56Constant.OAPIALCT56_TOKEN_KEY + "_" + driverIdentity, result.getToken(), result.getExpiryIn());
                redisUtil.set(OapiAlct56Constant.OAPIALCT56_REFRESHTOKEN_KEY + "_" + driverIdentity, result.getRefreshToken(), result.getExpiryIn());
                return result.getToken();
            }
            return StringUtils.EMPTY;
        } catch (Exception e) {
            log.info("OapiAlct56Service getRefreshtoken Exception :{} ",e.getMessage());
        }

        return StringUtils.EMPTY;
    }


    public AlctApiBaseResDTO uploadShippingImage(ShippingImageDTO shippingImageDTO) {

        AlctApiBaseResDTO result = new AlctApiBaseResDTO();
        String token = getToken(shippingImageDTO.getDriverCode());
        if (StringUtils.isEmpty(token)) {
            result.setMessage("请求Token为空");
            return result;
        }

        String path = StrUtil.EMPTY;
        if ("pod".equals(shippingImageDTO.getImageType())) {
            path = "/api/v1/openapi/shipments/podimages";
        } else {
            path = "/api/v1/openapi/shipments/images";
        }

        Map <String, String> headers = new HashMap <>();
        //最后在header中的格式(中间是英文空格)为Authorization:Bearer 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "Bearer " + token);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();

        try {
            log.info("上传辽宁航信装卸货及回单照片请求 -> {} {} {}", LN_TAX_DOMIAN + path,
                    shippingImageDTO.getShipmentCode(), shippingImageDTO.getImageType(), shippingImageDTO.getFileExt());
            HttpResponse response = HttpUtils.doPost(LN_TAX_DOMIAN, path, "POST", headers, querys, JSONUtil.toJsonStr(shippingImageDTO));
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                log.info("OapiAlct56Service uploadShippingImage Http code: :{}  | http header error msg:{} | Http body error msg: ",
                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                result.setCode(String.valueOf(stat));
                result.setMessage(response.getFirstHeader("X-Ca-Error-Message").toString());
                return result;
            }

            log.info("上传辽宁航信装卸货及回单照片回执 <- {}", stat);
            result.setCode("0");
            result.setMessage("操作成功");
            return result;
        } catch (Exception e) {
            log.info("OapiAlct56Service uploadShippingImage Exception :{} ",e.getMessage());
            result.setMessage(e.getMessage());
        }

        return result;
    }


//    public AlctApiBaseResDTO createShippingNote(BodyDTO bodyDTO){
//        AlctApiBaseResDTO result = new AlctApiBaseResDTO();
//        if(bodyDTO == null){
//            result.setMessage(" bodyDTO 为空");
//            return  result;
//        }
//        String token = getToken();
//        if(StringUtils.isEmpty(token)){
//            result.setMessage(" token 为空");
//            return  result;
//        }
//
//        String path = "/api/v1/openapi/shipments";
//        Map <String, String> headers = new HashMap <>();
//        //最后在header中的格式(中间是英文空格)为Authorization:Bearer 83359fd73fe94948385f570e3c139105
//        headers.put("Authorization", "Bearer " + token);
//        //根据API的要求，定义相对应的Content-Type
//        headers.put("Content-Type", "application/json; charset=UTF-8");
//        Map<String, String> querys = new HashMap<>();
//        // 拼装请求body的json字符串
//        //String enterpriseCode = HyCfgUtil.getCfgItem("liaoning_tax_report","enterpriseCode");
//        RootDTO rootDTO = new RootDTO();
//        HeadDTO headDTO = new HeadDTO();
//        headDTO.setSenderCode(LN_TAX_ENTERPRISE);
//        headDTO.setMessageReferenceNumber(UUID.randomUUID().toString().replace("-", ""));
//        headDTO.setMessageSendingDateTime(
//                DateUtils.dateTimeToStringT(new Date())
//        );
//        rootDTO.setHead(headDTO);
//        rootDTO.setBody(bodyDTO);
//        String bodys = JSONObject.toJSONString(rootDTO);
//
//        try {
//            log.info("创建辽宁航信税务运单请求 -> {} {}", LN_TAX_DOMIAN + path, bodys);
//            //String reportDomainUrl = HyCfgUtil.getCfgItem("liaoning_tax_report","reportDomainUrl");
//
//            HttpResponse response = HttpUtils.doPost(LN_TAX_DOMIAN, path, "POST", headers, querys, bodys);
//            int stat = response.getStatusLine().getStatusCode();
//            if(stat != 200){
//                log.info("OapiAlct56Service createShippingNote Http code: :{}  | http header error msg:{} | Http body error msg: ",
//                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
//                result.setCode(String.valueOf(stat));
//                result.setMessage(response.getFirstHeader("X-Ca-Error-Message").toString());
//                return result;
//            }
//            String res = EntityUtils.toString(response.getEntity());
//            log.info("创建辽宁航信税务运单回执, {}", res);
//            return JSONObject.parseObject(res, AlctApiBaseResDTO.class);
//        } catch (Exception e) {
//            log.info("OapiAlct56Service createShippingNote Exception :{} ",e.getMessage());
//            result.setMessage(e.getMessage());
//        }
//        return result;
//    }
}
